<!--
/**
@template: 见证项目统计分析
@author: ChaoPengWang(wangcp-a@glodon.com)
@update: 2022/4/16 9:36 PM
-->
<template>
  <div class="layout-wrapper layout-witness">
    <div class="layout-header layout-search">
      <el-form :inline="true"
               :model="searchForm"
               :rules="rules"
               ref="form"
               style="display:flex; flex-wrap: wrap; padding-right:10px">
        <el-form-item style="flex: 1; ">
                    <el-button type="primary" @click="download">导出{{ isDownloading ? "中..." : "" }}</el-button>
                    <el-button type="primary" @click="print" flex="1">打印</el-button>
        </el-form-item>


        <el-form-item label="见证日期" prop="witnessTime">
          <el-date-picker
            v-model="searchForm.witnessTime"
            class="ui-w260"
            unlink-panels
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :clearable="true"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"

          />

        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="getData">查询</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div ref="demo" style="display:none;"></div>
    <div class="statistics"  ref="statisticsTable">
      <div class="statistics-title">
        <div >
          见证人员见证项目小计
        </div>
      </div>

      <div class="statistics-table">
        <div class="statistics-table-tr statistics-table-title">
          <div>序号</div>
          <div>见证人员</div>
          <div>见证项目标段（包）数量</div>
        </div>
        <template v-for="(item, index) in projectVOList">
          <div :key="item.witnessUserName" class="statistics-table-tr statistics-table-data">
            <div>{{ index+1 }}</div>
            <div>{{ item.witnessUserName }}</div>
            <div>{{ item.projectCount }}</div>
          </div>
        </template>
        <div class="statistics-table-footer">
          <div>总计：{{projectAllCount}}</div>
          <div>每日平均项目数：{{averageProject}}</div>
          <div>每人每日平均项目数：{{averageUserProject}}</div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>

import moment from "moment";
import axios from "axios";

import css from './projectCss.js'
import { GZAPI_EvaluationTime } from "../../../../gz_plugin/api";

const date = moment().subtract(1, "day").format("YYYY-MM-DD");// 见证开始时间
export default {
  name:'projectStatistics',
  components: { },
  computed: {
  },
  props: {},
  data() {
    return {
      rules:{
        witnessTime: [
          { required: true, message: '请选择见证日期', trigger: 'change' }
        ]
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ],
        disabledDate(time){
          return time > new Date(date)
        }
      },
      isDownloading: false,
      searchForm: {
        witnessTime: [date, date]
      },
      tableLoading: false,
      projectVOList: [], // 人员统计列表
      averageProject: '', // 每日平均项目数
      averageUserProject: '', // 每人每日平均项目数
      projectAllCount: '', // 总见证项目数量
    };
  },
  watch: {
    searchForm: {
      deep: true,
      immediate: true,
      handler() {
        // 获取数据
        this.getData();
      }
    },
    "pageObj.currentPage"() {
      this.getData();
    },
    "pageObj.pageSize"() {
      this.getData();
    }
  },
  methods: {
    // 重置
    reset() {
      this.searchForm = {
        witnessTime: [date, date]
      };
    },

    // 获取表格数据
    async getData() {
      try {

        const { searchForm: { witnessTime } } = this;
        const params = {
          type: 3,
        };
        if (witnessTime && witnessTime.length === 2) {
          params.startTime = `${witnessTime[0]} 00:00:00`;
          params.endTime = `${witnessTime[1]} 23:59:59`;
        } else {
          this.$message.warning('请选择见证日期');
          return
        }

        this.tableLoading = true;
        const { code, data, message } = await GZAPI_EvaluationTime.projectStatistics(params);
        if (code === 0) {
          const {projectVOList, averageProject, averageUserProject, projectAllCount} = data;
          this.projectVOList = projectVOList;
          this.averageProject = averageProject;
          this.averageUserProject = averageUserProject;
          this.projectAllCount = projectAllCount;
        } else {
          this.$message.warning(message);
        }
      } catch (e) {
        console.error(e);
      } finally {
        this.tableLoading = false;
      }
    },

    async download() {
      try {
        if (this.isDownloading) {
          return;
        }
        const { searchForm: { witnessTime } } = this;
        const params = {
          type: 3,
        };
        if (witnessTime && witnessTime.length === 2) {
          params.startTime = `${witnessTime[0]} 00:00:00`;
          params.endTime = `${witnessTime[1]} 23:59:59`;
        } else {
          this.$message.warning('请选择见证日期');
          return
        }

        const instance = axios.create({
          contentType: "application/json;charset=UTF-8",
          responseType: "blob"
        });

        const res = await instance.post("/gdw/gz/witness/export/statisticalAnalysis", params);
        const fileName = "见证人员见证项目小计.xlsx";
        const csvData = new Blob([res.data], { type: "application/xlsx" });
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          window.navigator.msSaveOrOpenBlob(csvData, fileName);
        } else {
          const a = document.createElement("a");
          document.body.appendChild(a);
          a.style = "display: none";
          const url = window.URL.createObjectURL(csvData);
          a.href = url;
          a.download = fileName;
          a.click();
          a.remove();
          window.URL.revokeObjectURL(url);
        }

        let id = setTimeout(() => {
          clearTimeout(id);
          this.$message.success("导出成功");
        }, 100);
      } catch (e) {
        console.error(e);
      } finally {
        this.isDownloading = false;
      }
    },

    print() {
      const { searchForm: { witnessTime } } = this;
      if (!(witnessTime && witnessTime.length === 2)) {
        this.$message.warning('请选择见证日期');
        return;
      }
      let iframe = document.getElementById("iframeId");
      if (iframe) {
        this.$refs.demo.removeChild(iframe);
      }
      iframe = document.createElement("iframe");
      iframe.id = "iframeId";
      const style = document.createElement('style');
      style.innerText = css;


      iframe.onload = () => {
        const iframeBody = iframe.contentDocument || iframe.contentWindow.document;
        iframeBody.body.innerHTML = this.$refs.statisticsTable.innerHTML;
        iframeBody.body.appendChild(style);
        iframe.contentWindow.print();
      }

      this.$refs.demo.appendChild(iframe);

    },
  }
};
</script>
<style lang="scss" scoped>
.statistics{
  padding: 10px;
  box-sizing: border-box;
}

.statistics-title > div{
  font-size: 18px;
  line-height: 20px;
  font-weight: bolder;
  text-align: center;
  margin-bottom: 20px
}

.statistics-table{
  width: 100%;
  border-top: 1px solid #d2d2d2;
  border-left: 1px solid #d2d2d2;
  font-size: 14px;
  text-align: center;
  box-sizing: border-box;
}

.statistics-table > div{
  display: flex;
  width: 100%;
}
.statistics-table > div > div{
  padding: 8px 10px;
  border-bottom: 1px solid #d2d2d2;
  border-right: 1px solid #d2d2d2;
  line-height: 23px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
}

.statistics-table-tr>div:nth-child(1) {
  width: 10%;
}

.statistics-table-tr>div:nth-child(2) {
  width: 60%;
}

.statistics-table-tr>div:nth-child(3) {
  width: 30%;
}

.statistics-table-footer > div{
  width: calc(100% / 3);
}

.statistics-table-title{
  font-weight: 700;
  background-color: #e5e5e5;
}

</style>
